package com.opgea.crm.repository.security;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.opgea.crm.domain.entities.security.Resource;
import com.opgea.crm.domain.entities.security.ResourceDetails;
import com.opgea.crm.domain.entities.security.Role;
@Repository
public class RoleRepositoryImpl implements RoleRepository{

	@PersistenceContext
	EntityManager em;
	
	@Autowired
	ResourceRepository resourceRepo;
	
	@Override
	@Transactional
	public void create(Role role) {
		
		List<Resource> resources = resourceRepo.findAll();
		List<ResourceDetails> resourceDetailsList = new ArrayList<ResourceDetails>();
		for(Resource resource : resources){
			ResourceDetails rd = new ResourceDetails();
			rd.setRole(role);
			rd.setCreate(false);
			rd.setRead(false);
			rd.setUpdate(false);
			rd.setDelete(false);
			rd.setResource(resource);
			resourceDetailsList.add(rd);
		}
		role.setResourceDetailsList(resourceDetailsList);
		
		em.persist(role);
	}

	public Role find(Long id) {
		return em.find(Role.class, id);
	}

	@Override
	public List<Role> findAll() {
		String query = "SELECT r FROM Role r";
		return em.createQuery(query, Role.class).getResultList();
	}
	
	@Override
	public List<Role> findAllByName(String name) {
		String query = "SELECT r FROM Role r WHERE r.name like'"+name+"%'";
		return em.createQuery(query, Role.class).getResultList();
	}	

	@Override
	public void update(Role role) {
	}

	@Override
	public void remove(Long id) {
	}

}
